import feedparser
from pyramid.httpexceptions import HTTPFound, HTTPNotFound
from pyramid.view import view_config
from stockforecaster.config import settings
from stockforecaster.forms import AddCompaniesForm
from stockforecaster.lib import consts
from stockforecaster.lib.estimators import get_prediction
from stockforecaster.lib.pagination import Page
from stockforecaster.models import Company
from stockforecaster.tasks import fetch_all_stock_quotes
from webhelpers import text


@view_config(route_name='company.list', renderer='company/list.html')
def list_companies(request):
    companies = Page(Company.get_companies,
                     Company.count_companies,
                     settings.max_companies)
    return dict(companies=companies)


@view_config(route_name='company.view', renderer='company/view.html')
def view_company(request):
    company = Company.get_by_id(request.matchdict['id'])
    if not company:
        return HTTPNotFound('Company does not exist.')
    stock_quotes = Page(company.get_stock_quotes,
                        company.count_stock_quotes,
                        settings.max_stock_quotes)
    news = feedparser.parse(company.yahoo_finance_feed_url)
    q = company.get_all_stock_quotes()
    prediction = get_prediction(q)
    previous_company = company.get_previous_company()
    next_company = company.get_next_company()
    return dict(company=company,
                stock_quotes=stock_quotes,
                news=news,
                prediction=prediction,
                previous_company=previous_company,
                next_company=next_company)


@view_config(route_name='company.add', renderer='company/add.html')
def add_companies(request):
    form = AddCompaniesForm(request.POST)
    if 'add_companies' in request.POST and form.validate():
        companies_added = form.add_companies()
        request.session.flash('%s added. Stock quotes are being updated for these companies, please allow time to finish.' % text.plural(companies_added, 'company', 'companies', True), consts.SUCCESS)
        return HTTPFound(location=request.route_url('company.list'))
    return dict(form=form)


@view_config(route_name='company.remove')
def remove_company(request):
    company = Company.get_by_id(request.matchdict['id'])
    if not company:
        return HTTPNotFound('Company does not exist.')
    company.delete()
    request.session.flash('%s removed.' % company.name, consts.INFO)
    return HTTPFound(location=request.route_url('company.list'))


@view_config(route_name='fetch_quotes')
def fetch_quotes(request):
    fetch_all_stock_quotes.apply_async(countdown=10)
    request.session.flash('Stock quotes are being updated, please allow time to finish.', consts.INFO)
    return HTTPFound(location=request.route_url('company.list'))


@view_config(context=HTTPNotFound, renderer='error/not_found.html')
def error_not_found(request):
    return dict()


@view_config(context=Exception, renderer='error/catch_all.html')
def error_catch_all(request):
    if settings.debug:
        raise
    return dict()
